//
//  BaseCarKindView.m
//  cityCar
//
//  Created by yao on 14-10-29.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "BaseCarKindView.h"
#import "Connection.h"
#import "UIImageView+WebCache.h"
#import "WebColor.h"
#import "ForumDetailViewController.h"
#import "SeekBrandBaseViewCell.h"

@implementation BaseCarKindView

- (void)dealloc
{
    [_arraySection release];
    [_arrayRow release];
    [_meDictionary release];
    [_myTableView release];
    [_indexBar release];
    [_forumGather release];
    [_childrenDictionary release];
    [_stringName release];
    [_searchCarArray release];
    [_searchAreaArray release];
    [_searchCompositeArray release];
    [super dealloc];
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        
        // tableView初始化
        self.myTableView = [[UITableView alloc] init];
        [self addSubview:self.myTableView];
        [_myTableView release];
        
        // 容器类初始化
        self.arraySection = [NSMutableArray array];
        self.arrayRow = [NSMutableArray array];
        self.meDictionary = [NSMutableDictionary dictionary];
        self.childrenDictionary = [NSMutableDictionary dictionary];
        self.stringName = [NSString string];
        self.searchCarArray = [NSMutableArray array];
        self.searchAreaArray = [NSMutableArray array];
        self.searchCompositeArray = [NSMutableArray array];
    }
    return self;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    // 加载视图
    [self createView];
    // 加载数据
    [self startConnection];
    
}
- (void)createView
{
    if (self.temp == 1) {
        
        // self.temp = 1 代表论坛中的车系
        
        // 初始化第三方属性indexBar 签订协议
        self.indexBar = [[BATableView alloc] initWithFrame:self.bounds];
        self.indexBar.delegate = self;
        self.indexBar.childrenTableView.delegate = self;
        self.indexBar.childrenTableView.dataSource = self;
        
        
        //        self.indexBar.tableView.backgroundColor = [WebColor dimGray];
        
        // 抽屉收回的button
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.frame = CGRectMake(0, (self.frame.size.height - 60) / 2, 15, 60);
        //        button.backgroundColor = [WebColor cyan];
        [button setBackgroundImage:[UIImage imageNamed:@"side.png"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(scrollViewWillBeginDragging:) forControlEvents:UIControlEventTouchUpInside];
        [self.indexBar.childrenView addSubview:button];
        
        [self addSubview:self.indexBar];
        [_indexBar release];
        
    } else {
        
        // 否则 是论坛的地区和综合页面
        self.myTableView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
        self.myTableView.delegate = self;
        self.myTableView.dataSource = self;
    }
    
    
}

- (void)startConnection
{
    // 网络加载数据，并解析
    NSString *str = @"http://mrobot.pcauto.com.cn/v3/bbs/pcauto_v2_bbs_forum_tree";
    
    [Connection networkHandlerWith:str block:^(id result) {
        
        if (self.temp == 1) {
            // 解析车系页
            
            // 存放section的数组
            self.arraySection = [NSMutableArray array];
            
            NSMutableArray *arrayCar = [[[result objectForKey:@"children"] objectAtIndex:0] objectForKey:@"children"];
            
            for (NSDictionary *dic in arrayCar) {
                NSMutableArray *arr = [dic objectForKey:@"me"];
                NSString *str = [arr objectAtIndex:1];
                NSRange range = [str rangeOfString:@" "];
                str = [str substringToIndex:(range.location)];
                int flag = 1;
                for (int i = 0; i < self.arraySection.count && flag == 1; i++) {
                    if ([str isEqualToString:self.arraySection[i]]) {
                        flag = 0;
                    }
                }
                if (flag == 1) {
                    [self.arraySection addObject:str];
                }
            }
            
            for (int i = 0 ; i < self.arraySection.count; i++) {
                // 存放每个区里row的数组
                self.arrayRow = [NSMutableArray array];
                for (NSDictionary *dic in arrayCar) {
                    // 创建forumGather对象
                    self.forumGather = [[ForumGather alloc] init];
                    NSMutableArray *arr = [dic objectForKey:@"me"];
                    NSString *str = [arr objectAtIndex:1];
                    self.forumGather.Id = [arr objectAtIndex:0];
                    self.forumGather.image = [arr objectAtIndex:2];
                    if ([str hasPrefix:self.arraySection[i]]) {
                        NSRange range = [str rangeOfString:@" "];
                        str = [str substringFromIndex:(range.location + range.length)];
                        self.forumGather.name = str;
                        // 把forumGather对象加到每个区中row的数组里
                        [self.arrayRow addObject:self.forumGather];
                        
                        // 遍历每个row的children数组
                        NSMutableArray *array = [NSMutableArray array];
                        for (NSDictionary *dict in [dic objectForKey:@"children"]) {
                            self.forumGather = [[ForumGather alloc] init];
                            self.forumGather.Id = [[dict objectForKey:@"me"] objectAtIndex:0];
                            self.forumGather.name = [[dict objectForKey:@"me"] objectAtIndex:1];
                            //  把数组中的每个元素用forumGather对象存到临时数组array中
                            [array addObject:self.forumGather];
                            //  把Model类添加到要存入本地的数组中
                            [self.searchCarArray addObject:self.forumGather];
                            [_forumGather release];
                        }
                        // 然后把children数组存到childrenDictionary字典中
                        [self.childrenDictionary setValue:array forKey:str];
                    }
                    
                }
                // 把区名当做key，每个区所对应的row数组作为value，存到meDictionary字典中
                [self.meDictionary setValue:self.arrayRow forKey:self.arraySection[i]];
            }
            // 刷新数据
            [self.indexBar reloadData];
            
            // 写入本地
            static int flag = 1;
            if (flag == 1) {
                [self locationStore];
                flag = 0;
            }
            
            
        } else {
            // 解析地区和综合页
            
            // 存放section的数组
            self.arraySection = [NSMutableArray array];
            NSMutableArray *arrayCar = [NSMutableArray array];
            if (self.temp == 2) {
                arrayCar = [[[result objectForKey:@"children"] objectAtIndex:1] objectForKey:@"children"];
            } else {
                arrayCar = [[[result objectForKey:@"children"] objectAtIndex:2] objectForKey:@"children"];
            }
            
            for (NSDictionary *dic in arrayCar) {
                NSString *str = [[dic objectForKey:@"me"] objectAtIndex:1];
                [self.arraySection addObject:str];
                // 存放每个区里row的数组
                self.arrayRow = [NSMutableArray array];
                NSMutableArray *arr = [dic objectForKey:@"children"];
                for (NSDictionary *dic1 in arr) {
                    // 创建forumGather对象
                    self.forumGather = [[ForumGather alloc] init];
                    self.forumGather.Id = [[dic1 objectForKey:@"me"] firstObject];
                    self.forumGather.name = [[dic1 objectForKey:@"me"] objectAtIndex:1];
                    // 把forumGather对象加到每个区中row的数组里
                    [self.arrayRow addObject:self.forumGather];
                    if (self.temp == 2) {
                        [self.searchAreaArray addObject:self.forumGather];
                    } else {
                        [self.searchCompositeArray addObject:self.forumGather];
                    }
                }
                // 把区名当做key，每个区所对应的row数组作为value，存到meDictionary字典中
                [self.meDictionary setValue:self.arrayRow forKey:str];
            }
            
            // 刷新数据
            [self.myTableView reloadData];
            
            // 写入本地
            if (self.temp == 2) {
                static int flag = 1;
                if (flag == 1) {
                    [self locationStore];
                    flag = 0;
                }
            } else {
                static int flag = 1;
                if (flag == 1) {
                    [self locationStore];
                    flag = 0;
                }
                
            }
            
        }
        
    }];
}

// 本地存储
- (void)locationStore
{
    // 找到沙盒的路径
    NSLog(@"%@",NSHomeDirectory());
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSLog(@"%@", paths);
    
    // 获取documents的路径
    NSString *documentPath = [paths objectAtIndex:0];
    
    // 归档类，将一个实现了NSCoding协议的对象，写入本地
    NSString *carPath = [documentPath stringByAppendingPathComponent:@"car.aaa"];
    if (self.temp == 1) {
        BOOL carResult = [NSKeyedArchiver archiveRootObject:self.searchCarArray toFile:carPath];
        NSLog(@"车系写入本地：%d", carResult);
    } else if (self.temp == 2) {
        NSString *areaPath = [documentPath stringByAppendingPathComponent:@"area.aaa"];
        BOOL areaResult = [NSKeyedArchiver archiveRootObject:self.searchAreaArray toFile:areaPath];
        NSLog(@"地区写入本地：%d", areaResult);
    } else {
        NSString *areaPath = [documentPath stringByAppendingPathComponent:@"composite.aaa"];
        BOOL areaResult = [NSKeyedArchiver archiveRootObject:self.searchCompositeArray toFile:areaPath];
        NSLog(@"zonghe写入本地：%d", areaResult);
    }
    
    
}


#pragma mark BATableView
- (NSArray *)sectionIndexTitlesForABELTableView:(BATableView *)tableView
{
    // 返回给第三方一个索引数组
    return self.arraySection;
}

#pragma mark 协议方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    if (tableView == self.indexBar.childrenTableView) {
        // 是抽屉的tableView
        return 1;
    } else {
        // 否则，返回区数组的个数
        return self.arraySection.count;
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (tableView == self.indexBar.childrenTableView) {
        // 是抽屉的tableView，返回的区名为空
        return nil;
    } else {
        // 否则，返回区名
        return self.arraySection[section];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    if (tableView == self.indexBar.childrenTableView) {
        // 是抽屉的tableView，返回childrenDictionary字典所对应的value
        NSMutableArray *childrenArr = [self.childrenDictionary objectForKey:self.stringName];
        return childrenArr.count;
    } else {
        // 否则，返回meTictionary字典所对应的value
        NSMutableArray *arr = [self.meDictionary objectForKey:[self.arraySection objectAtIndex:(section)]];
        return arr.count;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (tableView == self.indexBar.childrenTableView) {
        // 如果是抽屉的tableView
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuseChildren"];
        if (cell == nil) {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reuseChildren"]autorelease];
        }
        // 返回childrenDictionary字典所对应的value
        ForumGather *forum = [[self.childrenDictionary objectForKey:self.stringName] objectAtIndex:indexPath.row];
        cell.textLabel.text = forum.name;
        cell.selectionStyle = 0;
        return cell;
        
    } else {
        // 否则，返回meTictionary字典所对应的value
        
        ForumGather *forum = [[self.meDictionary objectForKey:[self.arraySection objectAtIndex:(indexPath.section)]] objectAtIndex:indexPath.row];
        
        if (self.temp == 1) {
            // 如果是车系页
            SeekBrandBaseViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuseCar"];
            if (cell == nil) {
                cell = [[[SeekBrandBaseViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"reuseCar"] autorelease];
            }
            [cell.myImageView sd_setImageWithURL:[NSURL URLWithString:forum.image] placeholderImage:[UIImage imageNamed:@"NoPicture.png"]];
//            [cell.myImageView sd_setImageWithURL:[NSURL URLWithString:forum.image]];
            cell.label.text = forum.name;
            cell.selectionStyle = 0;
            return cell;
            
        } else {
            // 否则是 地区和综合页
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
            if (cell == nil) {
                cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reuse"] autorelease];
            }
            cell.textLabel.text = forum.name;
            cell.selectionStyle = 0;
            return cell;
        }
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (tableView == self.indexBar.tableView) {
        // 如果是车系页的Cell被点击
        
        // 执行动画，抽屉推出
        [UIView animateWithDuration:1 animations:^{
            self.indexBar.childrenView.frame = CGRectMake(70, 0, self.frame.size.width - 70, self.frame.size.height);
        }];
        
        // 记录一下点击的是哪个Cell，把Cell上的text存到self.stringName，传值用。
        NSString *str = [self.arraySection objectAtIndex:indexPath.section];
        NSMutableArray *arr = [self.meDictionary objectForKey:str];
        ForumGather *forum = [arr objectAtIndex:indexPath.row];
        self.stringName = forum.name;
        // 在这里刷新数据。
        //        self.indexBar.childrenTableView.delegate = self;
        [self.indexBar.childrenTableView reloadData];
    }
    else if(tableView == self.indexBar.childrenTableView) {
        // 如果是抽屉上的Cell被点击了
        
        ForumGather *forum = [[self.childrenDictionary objectForKey:self.stringName] objectAtIndex:indexPath.row];
        
        //        [self.recentlyArray addObject:forum];
        //        NSLog(@"最近访问的数组：%@", self.recentlyArray);
        
        self.block(forum.Id, forum.name);
        
//        // 通知中心发送通知
//        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
//        [center postNotificationName:@"abc" object:forum.Id userInfo:@{@"Name": forum.name}];
        
    } else {
        // 否则是，地区和综合的Cell被点击
        NSString *str = [self.arraySection objectAtIndex:indexPath.section];
        NSMutableArray *arr = [self.meDictionary objectForKey:str];
        ForumGather *forum = [arr objectAtIndex:indexPath.row];
        
        //        [self.recentlyArray addObject:forum];
        //        NSLog(@"最近访问diqu的数组：%@", self.recentlyArray);
        
        self.block(forum.Id, forum.name);
        
//        // 通知中心发送通知
//        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
//        [center postNotificationName:@"abc" object:forum.Id userInfo:@{@"Name": forum.name}];
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    // 抽屉收回方法
    if (scrollView != self.indexBar.childrenTableView) {
        //当不是在抽屉上的tableView上滑动时，执行动画
        
        [UIView animateWithDuration:1 animations:^{
            self.indexBar.childrenView.frame = CGRectMake(320, 0, self.frame.size.width - 70, self.frame.size.height);
        }];
    }
    
}




/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect
 {
 // Drawing code
 }
 */

@end
